package cn.com.tiptop.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.util.UUID;

/**
 * 
 * @author orange
 *
 */
public class FileUtils {
	/**
	 * 文件文末追加内容
	 * 
	 * @param filePath
	 * @param content
	 */
	public static boolean appendMethodFile(String filePath, String content) {
		try {
			// 打开一个随机访问文件流，按读写方式
			RandomAccessFile randomFile = new RandomAccessFile(filePath, "rw");
			// 文件长度，字节数
			long fileLength = randomFile.length();
			// 将写文件指针移到文件尾。
			randomFile.seek(fileLength);
			randomFile.writeBytes(content);
			randomFile.close();
			return true;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * 减少文末内容
	 * 
	 * @param filePath
	 * @param length
	 *            return 文末内容
	 */
	public static String subtractMethodFile(String filePath, int length) {

		int MAX_DATA_BLOCK = 4096;
		File file = new File(filePath);
		String path = file.getPath();
		int index = path.lastIndexOf("\\");
		if (!file.exists()) {
			return "";
		}
		String destFile = path.substring(0, index) + File.separatorChar + UUID.randomUUID().toString();

		try {

			File dest = new File(destFile);
			OutputStream out = new FileOutputStream(destFile);

			String str = "";
			InputStream in = new FileInputStream(filePath);
			str = readLastLine(file,length);
			int inputLen = in.available() - length;
			int offSet = 0;
			int i = 0;
			while (inputLen - offSet > 0) {
				byte[] cache = null;
				if(inputLen-offSet>=MAX_DATA_BLOCK) {
					cache = new byte[MAX_DATA_BLOCK];
				}else {
					cache = new byte[inputLen-offSet];
				}
				int l = in.read(cache);
				i++;
				offSet = i * MAX_DATA_BLOCK;
				out.write(cache, 0,l);
				out.flush();
			}
			in.close();
			out.close();
			file.delete();
			dest.renameTo(new File(filePath));
			return str;
		} catch (Exception e) {
			e.printStackTrace();
			if (new File(destFile).exists()) {
				new File(destFile).delete();
			}
			return "";
		}
	}

	@SuppressWarnings("resource")
	public static String readLastLine(File file,int length){
		try {
			if (!file.exists() || file.isDirectory() || !file.canRead()) {
				return "";
			}
			RandomAccessFile raf = null;
			raf = new RandomAccessFile(file, "r");
			long len = raf.length();
			if (len == 0L) {
				return "";
			} else {
				long pos = len - length;
				if(pos>0) {
					raf.seek(pos);
				}
				if (pos <= 0) {
					raf.seek(0);
				}
				byte[] bytes = new byte[(int) (len - pos)];
				raf.read(bytes);
				String md5 = new String(bytes);
				raf.close();
				return md5;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		} 
	}
}
